package com.skyline.courier.rpc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.skyline.common.utils.Assert;
import com.skyline.courier.rpc.annotation.ServiceProvider;
import com.skyline.courier.rpc.exception.RpcGenerateException;

public class ServiceRepository {
	private static final int DEFAULT_SERVICE_SIZE = 32;
	private Map<String, Object> serviceRepository = new HashMap<String, Object>(DEFAULT_SERVICE_SIZE);
	
	public void registerServices(List<?> services) throws Exception {
		for(Object service : services) {
			registerService(service);
		}
	}
	
	public void registerService(Object service) throws Exception {
		Assert.isNull(service, "service对象不能为null");

		Class<?> clazz = service.getClass();
		ServiceProvider provider = clazz.getAnnotation(ServiceProvider.class);

		if (provider == null) {
			return;
		}

		String[] serviceNames = getServiceNames(clazz, provider);

		addToRepository(serviceNames, service);
	}

	private void addToRepository(String[] serviceNames, Object service) {
		for(String serviceName : serviceNames) {
			serviceRepository.put(serviceName, service);
		}
	}
	
	private String[] getServiceNames(Class<?> clazz, ServiceProvider provider) throws RpcGenerateException {
		String[] names = provider.value();
		// 未配置服务名，则取其所有接口类名作为服务名。并且，只注册其直接实现接口，防止出现多个实现冲突的情况
		if (names.length == 1 && StringUtils.isBlank(names[0])) {
			Class<?>[] interfaces = clazz.getInterfaces();
			if (interfaces == null) {
				throw new RpcGenerateException("创建RPC的ServiceProvider失败，服务未实现任何接口，也未指定服务名");
			}

			String[] interfaceNames = new String[interfaces.length];
			for (int i = 0; i < interfaces.length; i++) {
				interfaceNames[i] = interfaces[i].getName();
			}

			return interfaceNames;
		} else {
			return names;
		}
	}

	public Object getService(String serviceName) {
		return serviceRepository.get(serviceName);
	}
}
